package com.cloud.pole.merchant.service.impl;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ace.cache.annotation.Cache;
import com.ace.cache.api.CacheAPI;
import com.cloud.pole.api.admin.AdminUserApi;
import com.cloud.pole.api.merchant.ShopMerchantUserApi;
import com.cloud.pole.api.permission.PermissionApi;
import com.cloud.pole.common.constant.CacheConstant;
import com.cloud.pole.common.constant.CommonConstants;
import com.cloud.pole.common.constant.UserConstant;
import com.cloud.pole.common.exception.BaseException;
import com.cloud.pole.common.exception.auth.UserInvalidException;
import com.cloud.pole.common.util.jwt.IJWTInfo;
import com.cloud.pole.common.util.jwt.JWTInfo;
import com.cloud.pole.common.util.jwt.JwtAuthenticationRequest;
import com.cloud.pole.common.util.jwt.JwtTokenUtil;
import com.cloud.pole.merchant.biz.ShopMerchantUserBiz;
import com.cloud.pole.merchant.controller.AuthController;
import com.cloud.pole.merchant.model.entity.ShopMerchantUser;
import com.cloud.pole.merchant.model.vo.FrontUser;
import com.cloud.pole.merchant.service.AuthService;
import com.cloud.pole.merchant.service.PermissionService;

import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private CacheAPI cacheAPI;
    @Autowired
    private ShopMerchantUserBiz userBiz;  
    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);
    
    @Override
    public String login(JwtAuthenticationRequest authenticationRequest) throws Exception {
    	ShopMerchantUserApi info = permissionService.validate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
        if (info.getUserId() != null && info.getUserId().intValue() > 0) {
        	JWTInfo jwtInfo = new JWTInfo(info.getUserName(), JWTInfo.USER_TYPE_MERCHANTT, info.getUserId().toString(), info.getNickName(), info.getRealName());
        	//把商户id写入token
        	jwtInfo.setUserAttr1(info.getMerchantId().toString());
        	return generateCatchToken(jwtInfo);
        }
        throw new UserInvalidException("用户不存在或账户密码错误!");
    }
    
    /**
     * 设置缓存信息
     * @param jwtInfo
     * @return 
     */
    private String generateCatchToken(JWTInfo jwtInfo) {
    	String token = JwtTokenUtil.generateToken(jwtInfo, CacheConstant.ADMIN_USER_TOKEN_EXPIRE * 60);
    	log.debug("写入缓存：token=" + token);
    	cacheAPI.set(CacheConstant.ADMIN_USER_TOKEN_KEY + ":" + jwtInfo.getUniqueName() , token, CacheConstant.ADMIN_USER_TOKEN_EXPIRE);
    	return token;
    }
    
    @Override
    public boolean validate(String token) throws Exception {
    	JWTInfo jwtInfo = (JWTInfo)JwtTokenUtil.getInfoFromToken(token);
    	String strCatchToken = cacheAPI.get(CacheConstant.ADMIN_USER_TOKEN_KEY + ":" + jwtInfo.getUniqueName());
    	log.debug("读取缓存：token=" + strCatchToken);

    	//获取用户信息，可以把用户账号无效等状态加到业务处理
    	if(StringUtils.isEmpty(strCatchToken)) {
    		throw new BaseException(CommonConstants.TOKEN_ERROR_EXPIRE_CODE, CommonConstants.TOKEN_ERROR_EXPIRE_MSSSAGE);
    	}
    	if(!StringUtils.equals(token, strCatchToken)) {
    		throw new BaseException(CommonConstants.TOKEN_ERROR_EXISTS_CODE, CommonConstants.TOKEN_ERROR_EXISTS_MSSSAGE);
    	}
    	return true;
    }

    @Override
    public String refresh(String oldToken) throws Exception {
    	IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(oldToken);
        return JwtTokenUtil.generateToken(jwtInfo, CacheConstant.ADMIN_USER_TOKEN_EXPIRE);
    }

	@Override
	public boolean checkUserName(String userName) throws Exception {
		// TODO Auto-generated method stub
//		User user = userBiz.getUserByUsername(userName);
//		if(user != null) {
//			return true;
//		}
		return false;
	}
}
